package com.lwm.transactional.xml.dao.impl;


import com.lwm.transactional.xml.dao.IAccountDAO;
import com.lwm.transactional.xml.pojo.AccountDO;
import com.lwm.transactional.xml.utils.ConnectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author liweimin
 * @date 2021/6/9 19:17
 * @since
 */
public class AccountDAOImpl implements IAccountDAO {

    private QueryRunner queryRunner;

    private ConnectionUtils connectionUtils;


    public void setQueryRunner(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    @Override
    public List<AccountDO> findAll() {
        try {
            return queryRunner.query(connectionUtils.getConnection(), "select * from account", new BeanListHandler<AccountDO>(AccountDO.class));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public AccountDO findAccountById(Integer id) {
        try {
            return queryRunner.query(connectionUtils.getConnection(), "select * from account where id = ?", new BeanHandler<AccountDO>(AccountDO.class), id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public AccountDO findAccountByName(String name) {
        List<AccountDO> list;
        try {
            list = queryRunner.query(connectionUtils.getConnection(), "select * from account where name = ?", new BeanListHandler<AccountDO>(AccountDO.class), name);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (list == null || list.size() < 1) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public int saveAccount(AccountDO accountDO) {
        try {
            return queryRunner.update(connectionUtils.getConnection(), "insert into  account(name,money) values(? ?)", accountDO.getName(), accountDO.getMoney());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int deleteAccount(Integer id) {
        try {
            return queryRunner.update(connectionUtils.getConnection(), "delete from account where id = ?", id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int updateAccount(AccountDO accountDO) {
        try {
            return queryRunner.update(connectionUtils.getConnection(), "update  account set name = ? ,money = ? where id = ?", accountDO.getName(), accountDO.getMoney(), accountDO.getId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
